/*
 * FileName: CyclicBarierDemo.java
 * Author:   zzw
 * Date:     2018年05月14日
 * Description:
 */
package com.zzw.thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class CyclicBarierDemo {

    public static class Soldier implements Runnable{

        private String soldier;
        private final CyclicBarrier cyclicBarrier;

        public Soldier(String soldier,CyclicBarrier cyclicBarrier) {
            this.soldier = soldier;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                cyclicBarrier.await();
                doWork();
                cyclicBarrier.await();
                System.out.println("------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

        private void doWork(){
            try {
                Thread.sleep(Math.abs(new Random().nextInt() % 10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务完成");
        }
    }

    public static class BarrierRun implements Runnable{
        boolean flag;
        int n;

        public BarrierRun(boolean flag, int n) {
            this.flag = flag;
            this.n = n;
        }

        @Override
        public void run() {
            if(flag){
                System.out.println("n:" + n + "完成任务");
            }
            else {
                System.out.println("n:" + n + "集合完毕");
                flag = true;
            }
        }
    }

    public static void main(String[] args) {
        final int n = 10;
        Thread[] allSoldier = new Thread[n];
        boolean flag = false;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(n,new BarrierRun(flag,n));
        System.out.println("集合队伍");
        for (int i = 0;i < n;++i){
            System.out.println("士兵" + i + "报道");
            allSoldier[i] = new Thread(new Soldier("士兵" + i,cyclicBarrier));
            allSoldier[i].start();
        }
    }
}
